package com.party.admin.web.controller.subject;

import com.google.common.base.Strings;
import com.party.admin.biz.article.ArticleBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.admin.biz.subject.SubjectDeleteBizService;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.common.paging.Page;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.article.Article;
import com.party.core.model.article.ArticleGroup;
import com.party.core.model.subject.Subject;
import com.party.core.model.subject.SubjectApply;
import com.party.core.model.user.User;
import com.party.core.service.article.IArticleGroupService;
import com.party.core.service.article.IArticleService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.subject.ISubjectApplyService;
import com.party.core.service.subject.ISubjectService;
import com.party.core.service.user.IUserService;
import com.party.core.utils.MyBeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * 专题
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "/subject/subject")
public class SubjectController {

    @Autowired
    private ISubjectService subjectService;

    @Autowired
    private ISubjectApplyService subjectApplyService;

    @Autowired
    private IUserService userService;

    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IArticleGroupService articleGroupService;

    @Autowired
    private CosBizService cosBizService;

    @Autowired
    private ArticleBizService articleBizService;

    @Autowired
    private SubjectDeleteBizService subjectDeleteBizService;

    protected static Logger logger = LoggerFactory.getLogger(SubjectController.class);


    /**
     * 专题管理
     *
     * @param subject
     * @param page
     * @return
     */
    @RequestMapping(value = "subjectList")
    public ModelAndView subjectList(Subject subject, Page page, CommonInput commonInput) {
        ModelAndView mv = new ModelAndView("subject/subjectList");
        subject.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        Map<String, Object> params = CommonInput.appendParams(commonInput);

        mv.addObject("input", commonInput);
        List<Subject> subjects = subjectService.webListPage(subject, params, page);
        for (Subject entity : subjects) {
            List<SubjectApply> applies = subjectApplyService.getBySubjectId(entity.getId());
            entity.setSubjectApplies(applies);

            String path = fileBizService.getUploadCIPath(entity.getMemberId(), "subject");
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(path + entity.getId());
            entity.setQrCodeUrl(qrCodeUrl);
        }
        mv.addObject("subjects", subjects);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 跳转至发布
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "subjectForm")
    public ModelAndView subjectForm(String id) {
        ModelAndView mv = new ModelAndView("subject/subjectForm");
        if (StringUtils.isNotEmpty(id)) {
            Subject subject = subjectService.get(id);
            mv.addObject("subject", subject);
        }
        return mv;
    }

    /**
     * 跳转至详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "subjectDetail")
    public ModelAndView subjectDetail(String id, Page page) {
        ModelAndView mv = new ModelAndView("subject/subjectDetail");
        if (StringUtils.isNotEmpty(id)) {
            Subject subject = subjectService.get(id);
            mv.addObject("subject", subject);

            page.setLimit(10);
            SubjectApply subjectApply = new SubjectApply();
            subjectApply.setSubjectId(id);
            subjectApply.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            List<SubjectApply> applies = subjectApplyService.listPage(subjectApply, page);
            for (SubjectApply apply : applies) {
                apply.setSubjectName(subject.getName());
            }
            mv.addObject("page", page);
            mv.addObject("applies", applies);
        }
        return mv;
    }

    /**
     * 发布保存
     *
     * @param subject
     * @param result
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult save(Subject subject, BindingResult result) throws Exception {
        AjaxResult ajaxResult = new AjaxResult();
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErros = result.getAllErrors();
            ajaxResult.setDescription(allErros.get(0).getDefaultMessage());
            return ajaxResult;
        }
        String memberId = Strings.isNullOrEmpty(subject.getMemberId()) ? RealmUtils.getCurrentUser().getId() : subject.getMemberId();
        if (StringUtils.isNotEmpty(subject.getId())) {
            Subject t = subjectService.get(subject.getId());
            MyBeanUtils.copyBeanNotNull2Bean(subject, t);
            subjectService.update(t);
            memberId = t.getMemberId();
        } else {
            User user = userService.findByLoginName("admin");
            subject.setCreateBy(user.getId());
            subject.setUpdateBy(user.getId());
            subjectService.insert(subject);
        }
        try {
            subject = subjectService.get(subject.getId());
            String filePath = fileBizService.getUploadCIPath(memberId, "subject");
            String content = "subject/subject_detail.html?id=" + subject.getId();
            fileBizService.uploadCloudOut(subject.getId(), filePath, content, memberId);
        } catch (Exception e) {
            logger.error("生成专题二维码异常", e);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 删除专题
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return new AjaxResult(false);
        }
        List<SubjectApply> applies = subjectApplyService.getBySubjectId(id);
        if (applies.size() > 0) {
            return new AjaxResult(false, "该专题下已有栏目");
        }
        boolean result = subjectDeleteBizService.deleteSubjectBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 复制专题
     *
     * @param subjectId  主题ID
     * @param memberId 选中的机构ID
     * @return
     */
    @ResponseBody
    @Transactional
    @RequestMapping(value = "copySubject")
    public AjaxResult copySubject(String subjectId, String memberId) {
        AjaxResult ajaxResult = new AjaxResult();
        if (StringUtils.isBlank(subjectId) || StringUtils.isBlank(memberId)) {
            ajaxResult.setSuccess(false);
            ajaxResult.setDescription("数据不能为空");
            return ajaxResult;
        }
        //复制指定主题
        Subject subject = subjectService.get(subjectId);
        clearData(subject);
        subject.setMemberId(memberId);
        String id = subjectService.insert(subject);

        try {
            subject = subjectService.get(subject.getId());
            String filePath = fileBizService.getUploadCIPath(memberId, "subject");
            String content = "subject/subject_detail.html?id=" + subject.getId();
            fileBizService.uploadCloudOut(subject.getId(), filePath, content, memberId);
        } catch (Exception e) {
            logger.error("生成专题二维码异常", e);
        }

        //复制获取到的栏目信息
        SubjectApply subjectApply = new SubjectApply();
        subjectApply.setSubjectId(subjectId);
        subjectApply.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        List<SubjectApply> applies = subjectApplyService.list(subjectApply);
        //复制每一个栏目的具体信息
        for (SubjectApply apply : applies) {
            //复制获取到的每一个栏目下的具体信息
            if (apply.getType().equals("article")) {
                //单篇文章
                Article article = articleService.get(apply.getTargetId());
                if (article != null) {
                    clearData(article);
                    article.setReadNum(0);
                    article.setMemberId(memberId);
                    String articleId = articleService.insert(article);

                    try {
                        articleBizService.uploadQrCode(memberId, article.getId());
                    } catch (Exception e) {
                        logger.error("生成文章二维码异常", e);
                    }

                    String url = apply.getUrl();
                    if (StringUtils.isNotEmpty(url)) {
                        String newUrl = url.substring(0, url.lastIndexOf("=") + 1) + articleId;
                        apply.setUrl(newUrl);
                    }
                    apply.setTargetId(articleId);
                }
            } else if (apply.getType().equals("channel")) {
                //文章列表（文章组 articleGroup）
                ArticleGroup articleGroup = articleGroupService.get(apply.getTargetId());
                clearData(articleGroup);
                articleGroup.setMemberId(memberId);
                String articleGroupId = articleGroupService.insert(articleGroup);

                Article article = new Article();
                article.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                article.setArticleGroupId(apply.getTargetId());
                List<Article> articles = articleService.listPage(article, null);
                for (Article a : articles) {
                    clearData(a);
                    a.setReadNum(0);
                    a.setMemberId(memberId);
                    a.setArticleGroupId(articleGroupId);
                    articleService.insert(a);

                    try {
                        articleBizService.uploadQrCode(memberId, a.getId());
                    } catch (Exception e) {
                        logger.error("生成文章二维码异常", e);
                    }
                }
                String url = apply.getUrl();
                if (StringUtils.isNotEmpty(url)) {
                    String newUrl = url.substring(0, url.lastIndexOf("=") + 1) + articleGroupId;
                    apply.setUrl(newUrl);
                }
                apply.setTargetId(articleGroupId);
            } else if (apply.getType().equals(SubjectApply.TYPE_URL)) {
                apply.setTargetId(null);
            }

            clearData(apply);
            apply.setSubjectId(id);
            apply.setMemberId(memberId);
            subjectApplyService.insert(apply);
        }
        ajaxResult.setSuccess(true);
        return ajaxResult;
    }

    /**
     * 清除数据
     *
     * @param obj 被清除的对象
     */
    private void clearData(BaseModel obj) {
        if (obj == null) {
            return;
        }
        obj.setId(null);
        obj.setCreateDate(null);
        obj.setUpdateDate(null);
    }

    @ResponseBody
    @RequestMapping("initQrCode")
    public AjaxResult initQrCode() {
        List<Subject> subjects = subjectService.list(new Subject());
        for (Subject subject : subjects) {
            String publisher = subject.getMemberId();
            if (StringUtils.isEmpty(publisher)) {
                continue;
            }
            String cloudFilePath = fileBizService.getUploadCIPath(publisher, "subject");

            /*** 详情二维码 ***/
            String localFilePath = publisher + "/subject/";
            String content = "subject/subject_detail.html?id=" + subject.getId();
            fileBizService.uploadCloudOut(subject.getId(), cloudFilePath, localFilePath, subject.getId(), content, publisher);
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping("checkQrCode")
    public AjaxResult checkQrCode(String subjectId) {
        if (StringUtils.isNotEmpty(subjectId)) {
            try {
                Subject subject = subjectService.get(subjectId);
                String filePath = fileBizService.getUploadCIPath(subject.getMemberId(), "subject");
                String content = "subject/subject_detail.html?id=" + subject.getId();
                fileBizService.uploadCloudOut(subject.getId(), filePath, content, subject.getMemberId());
            } catch (Exception e) {
                logger.error("生成专题二维码异常", e);
            }

            List<SubjectApply> subjectApplies = subjectApplyService.getBySubjectId(subjectId);
            for (SubjectApply subjectApply : subjectApplies) {
                if (StringUtils.isEmpty(subjectApply.getType())) {
                    continue;
                }
                if (subjectApply.getType().equals(SubjectApply.TYPE_ARTICLE_GROUP)) {
                    Article article = new Article();
                    article.setArticleGroupId(subjectApply.getTargetId());
                    List<Article> articles = articleService.list(article);
                    for (Article a : articles) {
                        try {
                            articleBizService.uploadQrCode(a.getMemberId(), a.getId());
                        } catch (Exception e) {
                            logger.error("文章二维码失败——专题id：" + subjectApply.getSubjectId() + ",栏目id：" + subjectApply.getId() + ",文章id：" + a.getId(), e);
                        }
                    }
                } else if (subjectApply.getType().equals(SubjectApply.TYPE_ARTICLE)) {
                    Article article = articleService.get(subjectApply.getTargetId());
                    if (article != null) {
                        try {
                            articleBizService.uploadQrCode(article.getMemberId(), article.getId());
                        } catch (Exception e) {
                            logger.error("文章二维码失败——专题id：" + subjectApply.getSubjectId() + ",栏目id：" + subjectApply.getId() + ",文章id：" + article.getId(), e);
                        }
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 初始化栏目包含域名的去掉
     * @return
     */
    @ResponseBody
    @RequestMapping("updateUrl")
    public AjaxResult updateUrl() {
        List<SubjectApply> subjectApplies = subjectApplyService.list(new SubjectApply());
        for (SubjectApply subjectApply : subjectApplies) {
            if (StringUtils.isEmpty(subjectApply.getType())) {
                continue;
            }
            if (subjectApply.getType().equals(SubjectApply.TYPE_ARTICLE) || subjectApply.getType().equals(SubjectApply.TYPE_ARTICLE_GROUP)) {
                String applyUrl = subjectApply.getUrl();
                int index = applyUrl.indexOf("/micWeb");
                if (index > 0) {
                    String subUrl = applyUrl.substring(index, applyUrl.length());
                    subjectApply.setUrl(subUrl);
                    subjectApplyService.update(subjectApply);
                }
            }
            if (subjectApply.getType().equals(SubjectApply.TYPE_URL)) {
                subjectApply.setTargetId(null);
                subjectApplyService.update(subjectApply);
            }
        }
        return AjaxResult.success();
    }
}
